package com.example.carrierapp.ui.main.find.detail;

import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.carrierapp.base.MVPBaseActivity;
import com.example.carrierapp.bean.find.FindGoodsDetailBean;
import com.example.carrierapp.config.ConstValue;
import com.example.carrierapp.event.GoodsRefreshEvent;
import com.example.carrierapp.ui.dialog.DialogUtils;
import com.example.carrierapp.ui.view.CountdownTextView;
import com.example.carrierapp.util.AppUtil;
import com.example.carrierapp.util.DisplayUtil;
import com.example.carrierapp.util.LogUtil;
import com.example.carrierapp.util.SpannableUtils;
import com.example.carrierapp.util.ToastUtils;
import com.example.lb.fingerdemo.R;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.text.NumberFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 找货详情
 */
public class FindGoodsDetailActivity extends MVPBaseActivity<FindGoodsDetailContract.View, FindGoodsDetailPresenter> implements FindGoodsDetailContract.View, CountdownTextView.OnTimeEndListener {
    public static final int TYPE_PRICE = 1;
    public static final int TYPE_ROB = 2;

    @BindView(R.id.tv_detail_name)
    TextView mTvGoodsName;
    @BindView(R.id.tv_find_count_down)
    CountdownTextView mTvCountDown;
    @BindView(R.id.tv_find_code)
    TextView mTvCode;

    @BindView(R.id.tv_find_address_start)
    TextView mTvAddressStart;
    @BindView(R.id.tv_find_address_start_detail)
    TextView mTvAddressDetailStart;
    @BindView(R.id.tv_find_address_end)
    TextView mTvAddressEnd;
    @BindView(R.id.tv_find_address_end_detail)
    TextView mTvAddressDetailEnd;
    @BindView(R.id.tv_find_distance)
    TextView mTvDistance;

    @BindView(R.id.tv_find_require_des)
    TextView mTvTransRequire;
    @BindView(R.id.tv_find_win_des)
    TextView mTvWinMode;
    @BindView(R.id.tv_find_fee_price)
    TextView mTvPriceTitle;
    @BindView(R.id.et_find_price)
    EditText mEtPrice;
    @BindView(R.id.tv_find_price)
    TextView mTvPrice;
    @BindView(R.id.tv_find_price_nofee)
    TextView mTvPriceNoFee;
    @BindView(R.id.tv_find_fee_des)
    TextView mTvFeeDes;
    @BindView(R.id.tv_find_insurance)
    TextView mTvInsurance;
    @BindView(R.id.tv_find_confirm)
    TextView mTvConfirm;


    private int mId;
    private FindGoodsDetailBean mFindGoodsDetailBean;
    private int mType;//1竞价2抢单

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showProgress();
        mPresenter.attachView(this);
        mPresenter.getFindGoodsDetail(mId);
    }

    @Override
    protected FindGoodsDetailPresenter createPresenter() {
        return new FindGoodsDetailPresenter(this);
    }

    @Override
    public int getContentView() {
        return R.layout.activity_find_detail;
    }

    @Override
    public String getTitleString() {
        return null;
    }

    @Override
    public void initView() {
        super.initView();
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        mId = getIntent().getIntExtra(ConstValue.ID, 0);
        mType = getIntent().getIntExtra(ConstValue.TYPE, 0);
        LogUtil.d("FindGoodsDetailActivity-" + mId + "-" + mType);

        switch (mType) {
            case TYPE_PRICE:
                setTitleString("竞价详情");
                mTvConfirm.setText("提交报价");
                mEtPrice.setVisibility(View.VISIBLE);
                break;
            case TYPE_ROB:
                setTitleString("抢单详情");
                mTvConfirm.setText("抢单");
                mTvPrice.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void initEvent() {
        super.initEvent();
        mEtPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mFindGoodsDetailBean != null) {
                    if (TextUtils.isEmpty(mEtPrice.getText().toString().trim())) {
                        mTvPriceNoFee.setText("0.0元/" + mFindGoodsDetailBean.unitName);
                    } else {
                        double a = Double.valueOf(mEtPrice.getText().toString().trim()) - Double.valueOf(mEtPrice.getText().toString().trim()) * mFindGoodsDetailBean.taxRate;
                        mTvPriceNoFee.setText(a + "元/" + mFindGoodsDetailBean.unitName);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @OnClick({R.id.tv_find_phone, R.id.tv_find_confirm})
    public void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.tv_find_phone:
                if (mFindGoodsDetailBean != null && !TextUtils.isEmpty(mFindGoodsDetailBean.phone)) {
                    new DialogUtils.Builder(this)
                            .setMessage("是否拨打电话？")
                            .setPositiveButton(null, null, new DialogUtils.CallbackListener() {
                                @Override
                                public void onClick(View v) {
                                    AppUtil.callNumber(FindGoodsDetailActivity.this, mFindGoodsDetailBean.phone);
                                }
                            }).creat().show();
                } else {
                    ToastUtils.showCenterToast(this, "抱歉，没有电话号码，请联系客服！");
                }
                break;

            case R.id.tv_find_confirm:
                confirmStart();
                break;
        }
    }

    private void confirmStart() {
        switch (mType) {
            case TYPE_PRICE:
                if (TextUtils.isEmpty(mEtPrice.getText().toString().trim())) {
                    ToastUtils.showCenterToast(this, "您还没有报价");
                    return;
                }
                String message1 = "含税运价为：" + mEtPrice.getText().toString().trim() + "元/" + mFindGoodsDetailBean.unitName + "\n确认报价?";

                Dialog dialog1 = new DialogUtils.Builder(this)
                        .setMessage(message1)
                        .setPositiveButton(null, null, new DialogUtils.CallbackListener() {
                            @Override
                            public void onClick(View v) {
                                showLoading("正在报价");
                                mPresenter.rabOrBidding(mFindGoodsDetailBean.id, mEtPrice.getText().toString().trim());
                            }
                        }).creat();
                dialog1.show();

                break;
            case TYPE_ROB:
                String message2 = "含税运价为：" + mFindGoodsDetailBean.maxPrice + "元/" + mFindGoodsDetailBean.unitName + "\n确认抢单?";
                Dialog dialog2 = new DialogUtils.Builder(this)
                        .setMessage(message2)
                        .setPositiveButton(null, null, new DialogUtils.CallbackListener() {
                            @Override
                            public void onClick(View v) {
                                showLoading("正在抢单");

                                mPresenter.rabOrBidding(mFindGoodsDetailBean.id, mFindGoodsDetailBean.maxPrice + "");
                            }
                        }).creat();
                dialog2.show();

                break;
        }
    }

    @Override
    public void getFindGoodsDetailSuccess(FindGoodsDetailBean bean) {
        dismissProgress();
        if (bean.isGroup)//u多綫運輸
        {
            new DialogUtils.Builder(this)
                    .setMessage("这是多线运输，请在电脑端操作！")
                    .setOutTouch(false)
                    .setPositiveButton(null, null, v -> {}).creat().show();
            confirmNoEnable();
        }

        mFindGoodsDetailBean = bean;
        mTvGoodsName.setText(bean.proName + " 总运量" + bean.proNum + bean.unitName);
        mTvCode.setText("资源编码 " + bean.bidCode);

        mTvAddressStart.setText(bean.startCity);
        mTvAddressDetailStart.setText(bean.startAddress);
        mTvAddressEnd.setText(bean.endCity);
        mTvAddressDetailEnd.setText(bean.endAddress);
//        winMode;//中标模式 1低价竞价2考评分3
        mTvWinMode.setText(bean.winModeName);
//        mTvDistance.setText("约" + bean.totalDistance + "公里");
        mTvDistance.setText(SpannableUtils.showDiffSize("约" + bean.totalDistance + "公里", 1, (bean.totalDistance + "").length() + 1, DisplayUtil.dip2px(this, 20)));
        mTvPriceTitle.setText("含税报价（元/" + bean.unitName + "）");

        mTvTransRequire.setText(TextUtils.isEmpty(bean.remark) ? "无" : bean.remark);
        if (bean.toEndSeconds != 0) {
            mTvCountDown.init((long) ((bean.toEndSeconds)), this);
            mTvCountDown.start();
        } else {
            mTvCountDown.setText("已经结束");
        }
//        mTvFeeDes.setText("不含税报价（税率为" + bean.taxRate + "）");

        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        BigDecimal db = new BigDecimal(bean.insurancePrice);
        mTvInsurance.setText(db.toPlainString() + "元/" + bean.unitName);
        if (mType != TYPE_PRICE) {
            mTvPrice.setText(bean.maxPrice + "元");
            mTvPriceNoFee.setText((bean.maxPrice - bean.maxPrice * bean.taxRate) + "元/" + bean.unitName);
        }
    }

    @Override
    protected boolean showBottomLine() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTvCountDown.stop();
    }

    @Override
    public void getFindGoodsDetailFailde(String msg) {
        dismissProgress();
        ToastUtils.showCenterToast(this, msg);
    }

    @Override
    public void rabOrBiddingSuccess(String msg) {
        switch (mType) {
            case TYPE_PRICE:
                ToastUtils.showCenterToast("竞价成功", this);
                break;
            case TYPE_ROB:
                ToastUtils.showCenterToast("抢单成功", this);
                break;
        }


        dismissProgress();
        finish();
        EventBus.getDefault().post(new GoodsRefreshEvent());

    }

    @Override
    public void rabOrBiddingFailde(String msg) {
        dismissProgress();
        ToastUtils.showCenterToast(msg, this);
    }

    @Override
    public void onTimeEnd() {
        mTvConfirm.setText("已经结束");
        confirmNoEnable();
    }

    private void confirmNoEnable()
    {
        mTvConfirm.setEnabled(false);
        mTvConfirm.setBackground(getResources().getDrawable(R.color.color_999999));
    }
}
